import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;


public class UdpHandler2 extends Thread{
	static ArrayList<InetAddress> arraylist = new ArrayList<InetAddress>();
	static ArrayList<DatagramPacket> packetlist = new ArrayList<DatagramPacket>();
	//static ArrayList<UdpHandler> handlerlist = new ArrayList<UdpHandler>();
	
	public static final int PEER_UDP_PORT = 16404;
	public static final int LOCAL_UDP_PORT = 16403;
	//private final static int port = 5060;
	private final static int bufsize = 1024;
	//private final static int bufsize = 1024;
	private DatagramSocket socket;
	
	public UdpHandler2(){
		init();
	}
	
	private void init(){
		try {
			socket = new DatagramSocket(LOCAL_UDP_PORT);
		} catch (SocketException e) {
			e.printStackTrace();
		}
		System.out.println("Ready........");
	}

	
	public void run(){
	    
		byte[] buf = new byte[bufsize];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		//synchronized (handlerlist) {
			//handlerlist.add(this);
		//}
		DatagramPacket packet2;
	    
		try{
			byte[] buf2 = new byte[bufsize];
			int datalength;
			//socket.receive(packet);
			//int source = packet.getPort();
	    	InetAddress source;
	    	//socket.connect(target,source);*/
		    while(true){
		    	//System.out.println(socket.isConnected());
		    	socket.receive(packet);
		    	source = packet.getAddress();
		    	buf2 = packet.getData();
		    	datalength = packet.getLength();
		    	//System.out.println("data length:" + packet.getLength() + "buffer length: " + packet.getData().length);
		    	synchronized (Member.addrList) {
		    		//arraylist.remove(target);
		    		for(int i = 0; i < Member.addrList.size(); i++){
		    			//if(!source.equals(Member.addrList.get(i))){
		    				//System.out.println(source + "\t" + arraylist.get(i));
		    				packet2 = Member.packetlist.get(i);
		    				packet2.setData(buf2, 0, datalength);
		    				socket.send(packet2);
		    			//}
		    			//packet.setAddress(arraylist.get(i));
		    			//packet.setPort(PEER_UDP_PORT);
				    	//socket.send(packet);
		    			//System.out.print("send!");
		    		}
		    		//arraylist.add(target);
		    	}
		    }
	    } catch (IOException e) {
			e.printStackTrace();
		}
	    
	}

}
